import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/HomeView.vue'),
    redirect: '/frontpage',
    meta: { requiresAuth: true },
    children: [
      {
        path: '/frontpage',
        name: 'FrontPage',
        component: () => import('../views/FrontPageView.vue'),
        meta: { title: '首页', requiresAuth: true }
      },
      {
        path: '/num',
        name: 'Num',
        component: () => import('../views/NumView.vue'),
        meta: { title: '号码管理', requiresAuth: true }
      },
      {
        path: '/transformation',
        name: 'transformation',
        component: () => import('../views/transformationView.vue'),
        meta: { title: '号码转换', requiresAuth: true }
      },
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/LoginView.vue'),
    meta: { title: '系统登录', guest: true }
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 导航控制核心逻辑
let currentAbortController = null

// 增强路由push方法
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  // 取消当前正在进行的导航
  if (currentAbortController) {
    currentAbortController.abort()
  }
  return originalPush.call(this, location).catch(err => {
    if (err.name !== 'NavigationDuplicated') throw err
  })
}

router.beforeEach(async (to, from, next) => {
  // 创建新的AbortController
  const controller = new AbortController()
  currentAbortController = controller

  try {
    // 认证检查
    if (to.meta.requiresAuth) {
      const token = localStorage.getItem('token')
      if (!token) {
        next({ path: '/login', query: { redirect: to.fullPath }})
        return
      }

      // 带取消功能的Token验证
      const valid = await validateToken(token, controller.signal)
      if (!valid) throw new Error('无效令牌')
    }

    // 访客页面检查
    if (to.meta.guest && localStorage.getItem('token')) {
      next('/')
      return
    }

    // 放行导航
    if (!controller.signal.aborted) {
      next()
    }
  } catch (error) {
    if (error.name === 'AbortError') {
      // 导航被主动取消，不处理
    } else {
      localStorage.removeItem('token')
      next('/login')
    }
  } finally {
    if (controller === currentAbortController) {
      currentAbortController = null
    }
  }
})

// 支持取消的Token验证
function validateToken(token, signal) {
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => resolve(!!token), 200)

    // 监听取消信号
    signal.addEventListener('abort', () => {
      clearTimeout(timer)
      reject(new DOMException('验证已取消', 'AbortError'))
    })
  })
}

export default router